<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="分享地址">
        <el-input v-model="dtShareUrl" readonly>
          <template #append>
            <el-button v-clipboard="dtShareUrl" type="primary">
              <span>复制链接</span>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <!-- <el-form-item>
        <canvas ref="qrCodeUrl" class="qrcode"></canvas>
      </el-form-item> -->
    </el-form>
  </Dialog>
</template>
<script setup lang="ts">
import { TaskApi, TaskVO } from '@/api/system/task'
import { FormGroupApi, FormGroupVO } from '@/api/system/formGroup'

import { DICT_TYPE } from '@/utils/dict'
import { getStrDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import QRCode from 'qrcode'

/** 表单任务 表单 */
defineOptions({ name: 'ShareForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formList = ref<FormGroupVO[]>([])

const formData = ref({
  id: undefined,
  dtName: undefined,
  dtType: undefined,
  dtRemark: undefined,
  dtBeginDate: undefined,
  dtEndDate: undefined,
  dtFormId: undefined,
  dtPeriodType: undefined,
  dtPeriodNum: undefined,
  dtReleaseTime: undefined,
  dtShareUrl: undefined,
  dtReleaseStatus: 1
})
const formRef = ref() // 表单 Ref
const dtShareUrl = ref('')
// 后端上传地址
const uploadUrl = import.meta.env.VITE_BASE_FILL_URL

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '分享'
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TaskApi.getTask(id)
      
      dtShareUrl.value = uploadUrl + formData.value.dtShareUrl
      QRCode.toCanvas(document.querySelector('.qrcode'), dtShareUrl.value)
    } finally {
      formLoading.value = false
    }
  }
  formList.value = await FormGroupApi.getUsedFormList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const onCopySuccess = () => {
  message.success(t('common.copySuccess'))
}

const onCopyError = () => {
  message.success(t('common.copyError'))
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    dtName: undefined,
    dtType: undefined,
    dtRemark: undefined,
    dtBeginDate: undefined,
    dtEndDate: undefined,
    dtFormId: undefined,
    dtPeriodType: undefined,
    dtPeriodNum: undefined,
    dtReleaseTime: undefined,
    dtShareUrl: undefined,
    dtReleaseStatus: 1
  }
  formRef.value?.resetFields()
}
</script>
